/*
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/

#include "ohos_gl_texture_framebuffer.h"
#include "ohos_gl_drawer.h"
#include "rtc_base/logging.h"

namespace webrtc {

GLTextureFrameBuffer::~GLTextureFrameBuffer() {
    if (textureID_) {
        glDeleteTextures(1, &textureID_);
    }
    if (fbo_) {
        glDeleteFramebuffers(1, &fbo_);
    }
}

bool GLTextureFrameBuffer::SetSize(int width, int height)
{
    if( width <= 0 || height <= 0) {
        RTC_LOG_T(LS_ERROR)<<"GLTextureFrameBuffer::SetSize, invalid width:"<<width<<", height:"<<height;
        return false;
    }
    if(width_ == width && height_ == height) {
        return true;
    }
    width_ = width;
    height_ = height;
    if(textureID_ == 0) {
        glGenTextures(1, &textureID_);
    }
    if(fbo_ == 0) {
        glGenFramebuffers(1, &fbo_);
    }

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureID_);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID_, 0);
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        RTC_LOG_T(LS_ERROR)<<"GLTextureFrameBuffer::SetSize, glCheckFramebufferStatus failed!";
        glBindRenderbuffer(GL_RENDERBUFFER, 0);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glBindTexture(GL_TEXTURE_2D, 0);
        return false;
    }
    glBindRenderbuffer(GL_RENDERBUFFER, 0);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    return true;
}

GLuint GLTextureFrameBuffer::GetFrameBufferID()
{
    return fbo_;
}

int GLTextureFrameBuffer::GetWidth()
{
    return width_;
}

int GLTextureFrameBuffer::GetHeight()
{
    return height_;
}

} // namespace webrtc


